package com.code.generate.controller;


import com.code.generate.model.JdbcConfig;
import com.code.generate.model.Project;
import com.code.generate.util.GCM_DB_util;
import com.code.generate.util.JsonRecordUtil;
import com.code.generate.vo.ResultData;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Slf4j
@RestController
@RequestMapping("/tableInfo")
public class TableInfoController {

    @RequestMapping(value = "/listTable", method = {RequestMethod.POST,RequestMethod.GET})
    public ResultData listTable(@RequestParam(value = "projectId")String projectId,
                                @RequestParam(value = "tableName",required = false)String tableName) throws Exception {
//        String projectId = getPara("projectId");
        Project project = Project.dao.findById(projectId);
        if (project.getJdbcConfigId() == null) {
            throw new Exception("项目没有配置数据源");
        }
//        String tableName = getPara("tableName");

        JdbcConfig jdbcConfig = JdbcConfig.dao.findById(project.getJdbcConfigId());
        DbPro dbPro = GCM_DB_util.getDb(project);
        List<Record> listTable = null;
        if (StrKit.notBlank(tableName)) {
            listTable = dbPro.find(
                    "SELECT * FROM INFORMATION_SCHEMA.tables WHERE TABLE_SCHEMA = ? and table_name like ?  ORDER BY table_name asc",
                    jdbcConfig.getDbName(), "%" + tableName + "%");
        } else {
            listTable = dbPro.find(
                    "SELECT * FROM INFORMATION_SCHEMA.tables WHERE TABLE_SCHEMA = ?  ORDER BY table_name asc",
                    jdbcConfig.getDbName());
        }
        System.out.println(listTable);
        log.info("listTable : {}",listTable);
        List listData = JsonRecordUtil.convertRecords(listTable);
        log.info("listData  : {}",listData);
        return ResultData.buildSuccess(listData);
    }
}
